package com.example.test1.controller;

import com.example.test1.annoation.UserLoginToken;
import com.example.test1.dto.UserLoginRp;
import com.example.test1.dto.UserLoginRpC01;
import com.example.test1.dto.UserLoginRq;
import com.example.test1.dto.UserTestRp;
import com.example.test1.mapper.FindIdAndUsernameByUsernameAndPasswordResult;
import com.example.test1.mapper.UserMapper;
import com.example.test1.utils.RedisUtil;
import com.example.test1.utils.TokenUtils;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/user")
@Api(tags = "User系列接口",description = "提供USER的接口")
public class UserController {

    static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserMapper userMapper;

    @Autowired
    TokenUtils tokenUtils;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("login")
    @ApiOperation(value = "用户登录接口")
    @ApiResponses({
            @ApiResponse(code=200,message = "200；查询成功")
    })
    public UserLoginRp login(@RequestBody @Validated @ApiParam("用户登录信息") UserLoginRq loginInfo){
        logger.info("请求的登录信息为:{}",loginInfo);
        UserLoginRp userLoginRp=new UserLoginRp();
        FindIdAndUsernameByUsernameAndPasswordResult result=
                userMapper.findIdAndUsernameByUsernameAndPassword(loginInfo.getUsername(),loginInfo.getPassword());
        if (result==null){
            logger.info("没有这样的用户");
            userLoginRp.setResult("NO_SUCH_USER");
        }else {
            logger.info("User信息为:{}",result);
            userLoginRp.setResult("LOGIN_SUCCESS");
            UserLoginRpC01 userInfo=new UserLoginRpC01();
            userInfo.setId(result.getId());
            userInfo.setUsername(result.getUsername());
            userInfo.setToken(tokenUtils.getToken(result));
            redisUtil.set(result.getId(),userInfo.getToken());
            userLoginRp.setUserInfo(userInfo);

        }
        return userLoginRp;
    }

//    @GetMapping("test")
//    public List<User> get(){
//        return userMapper.findAll();
//    }

    @GetMapping("test2")
    @UserLoginToken
    @ApiOperation(value = "用户是否登录的测试接口")
    public UserTestRp UserTest(){
        logger.info("测试成功");
        UserTestRp userTestRp=new UserTestRp();
        userTestRp.setInfo("测试成功");
        return userTestRp;
    }


}
